package br.usp.ime.ingpos.services;

import java.util.List;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.usp.ime.ingpos.modelo.AreaDePesquisa;
import br.usp.ime.ingpos.modelo.dao.AreaDePesquisaDAO;

@RequestScoped
@Component
public class AreaDePesquisaService
{
    private final AreaDePesquisaDAO areaDePesquisaDAO;

    public AreaDePesquisaService(
        AreaDePesquisaDAO areaDePesquisaDAO )
    {
        this.areaDePesquisaDAO = areaDePesquisaDAO;
    }

    public void inserirAreaDePesquisa(
        AreaDePesquisa areaDePesquisa )
    {
        if( areaDePesquisa.getAreaDePesquisaID() == null ) {
        	areaDePesquisaDAO.saveOrUpdate( areaDePesquisa );
        } else {
            AreaDePesquisa areaPersistente = this.getAreaDePesquisa( areaDePesquisa.getAreaDePesquisaID() );

            BeanUtils.copyProperties( areaDePesquisa, areaPersistente, new String[] {
                "areaDePesquisaID"
            } );

            areaDePesquisaDAO.saveOrUpdate( areaPersistente );
        }
    }

    public void deletarAreaDePesquisa(
        AreaDePesquisa areaDePesquisa )
    {
        final AreaDePesquisa areaPersistente = this.getAreaDePesquisa( areaDePesquisa.getAreaDePesquisaID() );
        areaDePesquisaDAO.delete( areaPersistente );
    }

    public List<AreaDePesquisa> procurarTodasAreasDePesquisa()
    {
        return areaDePesquisaDAO.findByCriteria( Order.asc( "nome" ) );
    }

    public List<AreaDePesquisa> procurarAreasDePesquisaAtivas()
    {
        return areaDePesquisaDAO.findByCriteria( Order.asc( "nome" ),
            Restrictions.eq( "inseridaPelaSecretaria", true ) );
    }

    public AreaDePesquisa procuraAreaDePesquisaPorNome(
        String nome )
    {
        List<AreaDePesquisa> areasDeInteresse = areaDePesquisaDAO.findByCriteria( Restrictions.eq(
            "nome", nome ) );

        if( areasDeInteresse.isEmpty() )
            return null;

        return areasDeInteresse.get( 0 );
    }

    public AreaDePesquisa getAreaDePesquisa(
        Long areaDePesquisaID )
    {
        return areaDePesquisaDAO.findById( areaDePesquisaID );
    }
}
